package com.ruoyi.framework.web.service;


import com.ruoyi.common.core.domain.entity.SysDept;

import com.ruoyi.framework.web.domain.server.SysAgentFrameword;
import com.ruoyi.framework.web.domain.server.SysStoreFrameword;
import com.ruoyi.framework.web.mapper.SysAgentFramewordMapper;
import com.ruoyi.framework.web.mapper.SysStoreFramewordMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

//    @Autowired
//    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysAgentFramewordMapper agentMapper;

    @Autowired
    private SysStoreFramewordMapper sysStoreMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
//        SysUser user = userService.selectUserByUserName(username);
        //用手机号登录
        SysUser user =  userMapper.selectUserByPhone(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        //判断当前用户是管理员 代理商 还是 商户

        Long deptId = user.getDeptId();
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String type = sysDept.getType();
        if (type.equals("1")) {
            //说明是代理商端，判断当前代理商是否处于可使用范围
            List<SysAgentFrameword> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("用户信息异常");
            }
            SysAgentFrameword sysAgent = agents.get(0);
            Date startTime = sysAgent.getStartTime();
            Date endTime = sysAgent.getEndTime();
            Date currentTime = new Date();
            if (currentTime.after(endTime) || currentTime.before(startTime)) {
                throw new ServiceException("当前用户不在可使用时间范围");
            }

            //判断当前状态
            if (!sysAgent.getStatus().equals("0")) {
                throw new ServiceException("该代理商已被禁用");
            }
        }
        else if (type.equals("2")) {
            //说明是商户
            List<SysStoreFrameword> sysStores = sysStoreMapper.selectSysStoreByDeptId(deptId);
            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("用户信息异常");
            }
            SysStoreFrameword sysStore = sysStores.get(0);
            //判断当前商户状态
            if(!sysStore.getStatus().equals("0")) {
                throw new ServiceException("该商户已被禁用");
            }


            Long agentId = sysStore.getAgentId();

            if (!agentId.equals(0l)) {
                //判断这个商户代理商是否有效
                SysAgentFrameword sysAgent = agentMapper.selectSysAgentById(agentId);
                Date startTime = sysAgent.getStartTime();
                Date endTime = sysAgent.getEndTime();
                Date currentTime = new Date();
                if (currentTime.after(endTime) || currentTime.before(startTime)) {
                    throw new ServiceException("您的代理商不在可使用时间范围");
                }

                //判断当前状态
                if (!sysAgent.getStatus().equals("0")) {
                    throw new ServiceException("该代理商已被禁用");
                }

            }

        }


            passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
